package cn.rongdao.jrkabao.ui.takephoto;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.ArrayMap;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.util.FRFileUtils;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mifengkong.appcommon.liveness.ILivenessHelper;
import cn.mifengkong.appcommon.liveness.SampleLivenessActivity;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.FRBaseTakePhotoActivity;
import cn.rongdao.jrkabao.bean.information.IdCardInfoByYituDistinguishBean;
import cn.rongdao.jrkabao.bean.message.ValidateIDCardPhotoBean;
import cn.rongdao.jrkabao.bean.takephoto.YituPhotoStorageBean;
import cn.rongdao.jrkabao.constant.InfoConstant;
import cn.rongdao.jrkabao.model.information.AddUserIdCardObversePhotoModel;
import cn.rongdao.jrkabao.model.information.AddUserIdCardOtherPhotoModel;
import cn.rongdao.jrkabao.model.message.IdCardPhotoModel;
import cn.rongdao.jrkabao.model.takephoto.YiTuPhotoStorageModel;
import cn.rongdao.jrkabao.ui.takephoto.uicomponent.ThreeTakePhotoComponent;
import cn.rongdao.jrkabao.util.permission.GoToPermissionSetting;

import static cn.rongdao.jrkabao.ui.IdentificationVerificate.IdentificationActivity.REQUEST_CODE_LIVENESSACTIVITY;

/**
 * Created by jiangyongxing on 2017/6/2.
 * 描述：一般步骤中，所需要的身份证验证
 */

public class CommonValidateIdCardPicActivity extends FRBaseTakePhotoActivity {

    public static final int PERMISSION_READ_EXTERNAL_STORAGE = 101;
    public static final int PERMISSION_WRITE_EXTERNAL_STORAGE = 102;
    public static final int PERMISSION_CAMERA = 103;

    private static final int HUMAN_PIC = 103;
    private static final int REVERSE_PIC = 104;
    private static final int OBVERSE_PIC = 105;

    @BindView(R.id.ltipl_desc_tv)
    TextView mLtiplDescTv;
    @BindView(R.id.ltipl_desc_close)
    ImageView mLtiplDescClose;
    @BindView(R.id.ltipl_desc_ll)
    LinearLayout mLtiplDescLl;
    @BindView(R.id.ltipl_titlebar)
    TitleBarUIComponent mTitleBarUIComponent;
    @BindView(R.id.ltipl_take_photo)
    ThreeTakePhotoComponent mThreeTakePhotoComponent;
    @BindView(R.id.ltipl_btn)
    TextView submitBtn;

    private AlertDialog retryDialog;//活体检测出现错误的时候，显示这个dialog

    private String mHuman;//手持身份证的照片转Base64
    private String mReverse;//身份证背面的照片转Base64
    private String mObverse;//身份证正面的照片转Base64
    //    private String suffix;
    private Map<String, String> hashMap = new ArrayMap<>();
    private Map<String, String> mUserInfoMap = new ArrayMap<>();
    private SparseArray<String> picStatus = new SparseArray<>();

    private String bottomTextViewContent = "下一步";


    public static void start(Context context) {
        FRStartActivity.start(context, CommonValidateIdCardPicActivity.class);
    }

    @Override
    protected int layoutRes() {
        return R.layout.activity_take_idcard_photo_loan;
    }

    @Override
    protected void initView() {
        super.initView();
        initData();
        initTitleBar();
        initListener();
        initDialog();
    }

    private void initDialog() {
        initLivenessDialog();
    }

    private void initLivenessDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("温馨提示");
        builder.setMessage("活体检测失败，请重试");
        builder.setCancelable(true);

        // 拒绝, 退出应用
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        builder.setPositiveButton("重试", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startLivenessActivity();
            }
        });

        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        retryDialog = builder.create();
        retryDialog.setCanceledOnTouchOutside(false);
    }


    private void initData() {
        IdCardPhotoModel.getInstance().execute(null, new FRBaseObserver<ValidateIDCardPhotoBean>(this, "正在加载，请稍候...") {
            @Override
            protected void onBaseNext(ValidateIDCardPhotoBean data) {
                mAlbumStatus = data.getIs_open_photos();
                mThreeTakePhotoComponent.setPositivePic(data.getObverse());
                mThreeTakePhotoComponent.setNegativePic(data.getReverse());
                mThreeTakePhotoComponent.setHandheldPic(data.getHuman());

                initSparseArrayData(data);
                picStatusCorrectAndStartLivebessActivity();
            }

            @Override
            protected void onBaseError(Throwable t) {
                handingExceptions(t, false);
            }
        });
    }

    /**
     * 获取用户上传照片的状态，就是看用户上传了几张照片了。
     *
     * @param data
     */
    private void initSparseArrayData(ValidateIDCardPhotoBean data) {
        if (!TextUtils.isEmpty(data.getObverse())) {
            picStatus.put(OBVERSE_PIC, data.getObverse());
        }
        if (!TextUtils.isEmpty(data.getReverse())) {
            picStatus.put(REVERSE_PIC, data.getReverse());
        }
        if (!TextUtils.isEmpty(data.getHuman())) {
            picStatus.put(HUMAN_PIC, data.getHuman());
        }
    }


    private void initListener() {
        mThreeTakePhotoComponent.setImageViewOnclickListener(new ThreeTakePhotoComponent.ImageViewOnclickListener() {
            @Override
            public void onPositivePicClickListener(View view) {
                takeOrSelectPhoto(PIC_WITHOUT_PERSON_FRONT);
            }

            @Override
            public void onNegativePicClickListener(View view) {
                takeOrSelectPhoto(PIC_WITHOUT_PERSON_OPPOSITE);
            }

            @Override
            public void onHandheldPicClickListener(View view) {
                takeOrSelectPhoto(PIC_WITH_PERSON);
            }
        });
    }

    private void takeOrSelectPhoto(int type) {
        if (!lackPermission()) {
            picType = type;
            caremaOptionsDialog.show();
        }
    }

    private void initTitleBar() {
        mTitleBarUIComponent.initLeftBackBlack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mTitleBarUIComponent.initTitleBlack("身份证照片");
        mTitleBarUIComponent.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
    }


    @Override
    protected void successReturnPicpath(String picPath, String suffix, String imageViewBase64) {
        hashMap.put("suffix", suffix);
        try {
            //将图片进行BASE64加密，然后再传输
            if (picType == PIC_WITHOUT_PERSON_FRONT) {
                mThreeTakePhotoComponent.setPositivePic(picPath);
                mObverse = imageViewBase64;
                picStatus.remove(OBVERSE_PIC);
            } else if (picType == PIC_WITHOUT_PERSON_OPPOSITE) {
                mReverse = imageViewBase64;
                mThreeTakePhotoComponent.setNegativePic(picPath);
                picStatus.remove(REVERSE_PIC);
            } else if (picType == PIC_WITH_PERSON) {
                mHuman = imageViewBase64;
                mThreeTakePhotoComponent.setHandheldPic(picPath);
                picStatus.remove(HUMAN_PIC);
            }
            submitBtn.setText("确认提交");
        } catch (Exception e) {
            Toast.makeText(this, "选择图片文件不正确", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }


    @OnClick(R.id.ltipl_btn)
    public void onViewClicked() {
        if (submitBtn.getText().toString().equals(bottomTextViewContent)) {
            picStatusCorrectAndStartLivebessActivity();
            return;
        }
        if (hasTakenPictures()) return;
        if (!TextUtils.isEmpty(mObverse)) {
            hashMap.put(InfoConstant.OBVERSE, mObverse);
            picStatus.put(OBVERSE_PIC, "mObverse");
        }
        if (!TextUtils.isEmpty(mReverse)) {
            picStatus.put(REVERSE_PIC, "mReverse");
            hashMap.put(InfoConstant.REVERSE, mReverse);
        }
        if (!TextUtils.isEmpty(mHuman)) {
            picStatus.put(HUMAN_PIC, "mHuman");
            hashMap.put(InfoConstant.HUMAN, mHuman);
        }
        uploadPicData(hashMap);
    }

    /**
     * 用户是否拍过照片，防止用户没有拍过照片就去点击提交按钮，这个不必要的提交终止
     *
     * @return
     */
    boolean hasTakenPictures() {
        if (hashMap.size() < 1)
            return true;
        return false;
    }

    private void uploadPicData(final Map<String, String> hashMap) {
        if (hashMap.containsKey(InfoConstant.OBVERSE)) {//上传带有身份证正面照片的
            //上传不带正面的照片
            AddUserIdCardObversePhotoModel.getInstance().execute(hashMap, new FRBaseObserver<IdCardInfoByYituDistinguishBean>(this, "正在上传，请稍候...") {
                @Override
                protected void onBaseNext(IdCardInfoByYituDistinguishBean data) {
                    FRToast.showToastSafe("上传成功");
                    picStatusCorrectAndStartLivebessActivity();
                    resetPicData();
                }

                @Override
                protected void onBaseError(Throwable t) {
                    super.onBaseError(t);
                    //将正面照图片重置
                    mThreeTakePhotoComponent.removePositivePic();
                    mObverse = "";
                    picStatus.delete(OBVERSE_PIC);
                    hashMap.remove(InfoConstant.OBVERSE);
                }
            });

        } else {
            AddUserIdCardOtherPhotoModel.getInstance().execute(hashMap, new FRBaseObserver<String>(this, "正在上传，请稍候...") {

                @Override
                protected void onBaseNext(String data) {
                    FRToast.showToastSafe("提交成功");
                    picStatusCorrectAndStartLivebessActivity();
                    resetPicData();
                }
            });
        }
    }

    /**
     * 提交成功以后，重置用户的照片信息，防止重复提交，减少用户上传的流量和时间
     */
    private void resetPicData() {
        mObverse = "";
        mReverse = "";
        mHuman = "";
        hashMap.clear();
    }

    private void picStatusCorrectAndStartLivebessActivity() {
        if (picStatus.size() == 3) {
            submitBtn.setText(bottomTextViewContent);
            startLivenessActivity();
        }
    }


    private void startLivenessActivity() {
        if (!requestPermission()) {
            GoToPermissionSetting.showSnackBar(this, this.mTitleBarUIComponent);
            return;
        }
        Intent i = new Intent(this, SampleLivenessActivity.class);
        startActivityForResult(i, REQUEST_CODE_LIVENESSACTIVITY);
    }

    private boolean requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_WRITE_EXTERNAL_STORAGE);
            return false;
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_READ_EXTERNAL_STORAGE);
            return false;
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSION_CAMERA);
            return false;
        }

        return true;
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        try {
            switch (requestCode) {
                case PERMISSION_CAMERA: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    } else {
                        Toast.makeText(this, "没有摄像头权限我什么都做不了哦!", Toast.LENGTH_LONG).show();
                    }
                    break;
                }
                case PERMISSION_READ_EXTERNAL_STORAGE: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    } else {
                        Toast.makeText(this, "请打开存储读写权限，确保APP正常运行", Toast.LENGTH_LONG).show();
                    }
                    break;
                }
                case PERMISSION_WRITE_EXTERNAL_STORAGE: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    } else {
                        Toast.makeText(this, "请打开存储读写权限，确保APP正常运行", Toast.LENGTH_LONG).show();
                    }
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_LIVENESSACTIVITY:
                //表示是活体检测SDK自动返回的(成功或者是失败两种情况)
                if (data == null)
                    return;
                boolean mIsSuccess = data.getBooleanExtra(ILivenessHelper.LIVENESSACTIVITYSUCCESSTAG, false);
                if (mIsSuccess) {
                    String base64Data1 = FRFileUtils.read("base64Data1");
                    judgeWhetherTheSamePerson(base64Data1);
                } else {
                    retryDialog.show();
                }
                break;
        }
    }

    /**
     * 依图SDK返回的照片和身份证对比，判断是否同一个人
     *
     * @param base64Data1
     */
    private void judgeWhetherTheSamePerson(String base64Data1) {
        mUserInfoMap.put("suffix", "jpeg");
        mUserInfoMap.put("query_image_1", FRString.valueOf(base64Data1));
        YiTuPhotoStorageModel.getInstance().execute(mUserInfoMap, new FRBaseObserver<YituPhotoStorageBean>(this, "正在上传，请稍候") {
            @Override
            protected void onBaseNext(YituPhotoStorageBean data) {
                FRToast.showToastSafe("身份信息保存成功");
                finish();
            }

            @Override
            protected void onBaseError(Throwable t) {
                super.onBaseError(t);
                finish();
            }
        });
    }
}